package com.example.backgroundmanager.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backgroundmanager.common.Result;
import com.example.backgroundmanager.entity.Article;
import com.example.backgroundmanager.service.ArticleService;
import com.example.backgroundmanager.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private ArticleService articleService;



    @PostMapping
    public Result save(@RequestBody Article article) {
        if(article.getId()==null){
            article.setTime(DateUtil.now());
            article.setUser(TokenUtils.getCurrentUser().getNickname());
        }
        return Result.success(articleService.saveOrUpdate(article));
    }

    @PutMapping
    public Result update(@RequestBody Article article) {
        return Result.success(articleService.updateById(article));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        articleService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result findById(@PathVariable Long id) {
        return Result.success(articleService.getById(id));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(articleService.list());
    }

    @GetMapping("/page")
    public IPage<Article> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize,
                                   @RequestParam(defaultValue = "") String name,
                                @RequestParam(defaultValue = "") String user){
        IPage<Article> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Article> queryWrapper=new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if(!"".equals(user)){
            queryWrapper.like("user",user);
        }
        if(!"".equals(name)){
            queryWrapper.like("name",name);
        }
        queryWrapper.orderByDesc("id");

        queryWrapper.orderByDesc("id");
        return articleService.page(page,queryWrapper);
    }


}
